package encaps.action;

import encaps.entities.Grant;
import encaps.entities.Role;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.utils.EntityUtil;
import encaps.utils.XMLHelper;
import java.util.Date;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class LogoutAction extends Action {

    public static final String LOGOUT = "logout";
    private ActionContext actionContext;

    public LogoutAction(ActionContext context, Grant requiredGrant) {
        actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            JMSUtil.sendLogMessage(Log.LOGOUT,
                    EntityUtil.getUserHome().findByLogin(actionContext.getUserLogin()).getID(),
                    actionContext.getUserLogin(), new Date(), null, null, null);

            actionContext.setUserLogin(null);
            actionContext.setUserRole(Role.GUEST);
            Element e = XMLHelper.createTextMessage(Labels.getLabel(Labels.WELCOME));
            return e;
        } catch (FinderException ex) {
            return XMLHelper.createTextMessage(Labels.getLabel(Labels.AUTHORIZATION_FAILED_NO_SUCH_USER_MESSAGE));
        } catch (NamingException ex) {
            throw new ActionExecutionException("Can not find UserHome", ex);
        }
    }
}
